// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#pragma once

#include <cstddef>
#include <cassert>

#include "Logger.h"

namespace Hdfs {

/**
 * Fill the buffer with "012345678\n".
 * @param buffer The buffer to be filled.
 * @param size The size of the buffer.
 * @param offset Start offset of the content to be filled.
 */
static inline void FillBuffer(char * buffer, size_t size, size_t offset) {
	int64_t todo = size;

	char c;
	while (todo-- > 0) {
		c = offset++ % 10;
		c = c < 9 ? c + '0' : '\n';
		*buffer++ = c;
	}
}

/**
 * Check the content of buffer if it is filled with "012345678\n"
 * @param buffer The buffer to be checked.
 * @param size The size of buffer.
 * @param offset Start offset of the content in buffer.
 * @return Return true if the content of buffer is filled with expected data.
 */
static inline bool CheckBuffer(const char * buffer, size_t size,
		size_t offset) {
	int64_t todo = size;

	char c;
	while (todo-- > 0) {
		c = offset++ % 10;
		c = c < 9 ? c + '0' : '\n';
		if (*buffer++ != c) {
			return false;
		}
	}

	return true;
}

static inline const char * GetEnv(const char * key, const char * defaultValue) {
	const char * retval = getenv(key);
	if (retval && strlen(retval) > 0) {
		return retval;
	}
	return defaultValue;
}

}

#define DebugException(function) \
    try { \
        function ; \
    } catch (const Hdfs::HdfsException & e) { \
        std::string buffer; \
        LOG(LOG_ERROR, "DEBUG:\n%s", Hdfs::Internal::GetExceptionDetail(e, buffer)); \
        throw; \
    } catch (const std::exception & e) { \
        LOG(LOG_ERROR, "DEBUG:\n%s", e.what()); \
        throw; \
    }
